package com.foftact.etf;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ETF基金行情控制器
 * 处理前端的HTTP请求，提供ETF基金行情数据的API接口
 */
@RestController
@RequestMapping("/api/etf")
public class ETFListController {
    private static final Logger logger = LoggerFactory.getLogger(ETFListController.class);

    @Autowired
    private ETFListService etfListService;

    /**
     * 抓取并保存ETF基金行情数据
     * @return 操作结果
     */
    @PostMapping("/fetch")
    public ResponseEntity<Map<String, Object>> fetchETFData() {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("接收到抓取ETF基金行情数据的请求");
            int savedCount = etfListService.fetchAndSaveETFListData();
            result.put("success", true);
            result.put("message", "ETF基金行情数据抓取成功");
            result.put("data", savedCount);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("抓取ETF基金行情数据失败", e);
            result.put("success", false);
            result.put("message", "ETF基金行情数据抓取失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 根据基金代码获取ETF数据
     * @param code 基金代码
     * @return ETF数据对象
     */
    @GetMapping("/code/{code}")
    public ResponseEntity<Map<String, Object>> getETFByCode(@PathVariable("code") String code) {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("接收到根据基金代码获取ETF数据的请求，code: {}", code);
            ETFList etfList = etfListService.getETFByCode(code);
            if (etfList != null) {
                result.put("success", true);
                result.put("message", "获取ETF数据成功");
                result.put("data", etfList);
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "未找到该基金代码的数据");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }
        } catch (Exception e) {
            logger.error("根据基金代码获取ETF数据失败，code: {}", code, e);
            result.put("success", false);
            result.put("message", "获取ETF数据失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 获取所有ETF数据
     * @return ETF数据列表
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getAllETFList() {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("接收到获取所有ETF数据的请求");
            List<ETFList> etfListList = etfListService.getAllETFList();
            result.put("success", true);
            result.put("message", "获取所有ETF数据成功");
            result.put("data", etfListList);
            result.put("total", etfListList.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取所有ETF数据失败", e);
            result.put("success", false);
            result.put("message", "获取ETF数据失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 保存单个ETF数据
     * @param etfList ETF数据对象
     * @return 操作结果
     */
    @PostMapping("/save")
    public ResponseEntity<Map<String, Object>> saveETFList(@RequestBody ETFList etfList) {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("接收到保存ETF数据的请求，code: {}", etfList.getCode());
            boolean saved = etfListService.saveETFList(etfList);
            if (saved) {
                result.put("success", true);
                result.put("message", "ETF数据保存成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "ETF数据保存失败");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
            }
        } catch (Exception e) {
            logger.error("保存ETF数据失败", e);
            result.put("success", false);
            result.put("message", "保存ETF数据失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 更新ETF数据
     * @param etfList ETF数据对象
     * @return 操作结果
     */
    @PutMapping("/update")
    public ResponseEntity<Map<String, Object>> updateETFList(@RequestBody ETFList etfList) {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("接收到更新ETF数据的请求，code: {}", etfList.getCode());
            boolean updated = etfListService.updateETFList(etfList);
            if (updated) {
                result.put("success", true);
                result.put("message", "ETF数据更新成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "ETF数据更新失败");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
            }
        } catch (Exception e) {
            logger.error("更新ETF数据失败", e);
            result.put("success", false);
            result.put("message", "更新ETF数据失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 根据基金代码删除ETF数据
     * @param code 基金代码
     * @return 操作结果
     */
    @DeleteMapping("/delete/{code}")
    public ResponseEntity<Map<String, Object>> deleteETFByCode(@PathVariable("code") String code) {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("接收到删除ETF数据的请求，code: {}", code);
            boolean deleted = etfListService.deleteETFByCode(code);
            if (deleted) {
                result.put("success", true);
                result.put("message", "ETF数据删除成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "ETF数据删除失败");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
            }
        } catch (Exception e) {
            logger.error("删除ETF数据失败，code: {}", code, e);
            result.put("success", false);
            result.put("message", "删除ETF数据失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 清空ETF表
     * @return 操作结果
     */
    @DeleteMapping("/clear")
    public ResponseEntity<Map<String, Object>> clearETFList() {
        Map<String, Object> result = new HashMap<>();
        try {
            logger.info("接收到清空ETF表的请求");
            boolean cleared = etfListService.clearETFList();
            if (cleared) {
                result.put("success", true);
                result.put("message", "ETF表清空成功");
                return ResponseEntity.ok(result);
            } else {
                result.put("success", false);
                result.put("message", "ETF表清空失败");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
            }
        } catch (Exception e) {
            logger.error("清空ETF表失败", e);
            result.put("success", false);
            result.put("message", "清空ETF表失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }
}